package com.lc1993929.bean;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by LiuChang on 2017/5/17.
 */
public class HelloWorld {
    private static final Logger logger = LoggerFactory.getLogger(HelloWorld.class);

    public static void main(String[] args) {
        /**
         * 1、获取安全管理器
         * 2、获取用户
         * 3、用户登录验证
         * 4、权限管理
         * 5、角色管理
         * 5、session:用户登陆到用户退出，作用域
         */

        //1、获取安全管理器
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        //需要设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);

        //获取Subject对象，即将登陆的用户
        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();

        session.setAttribute("name", "大天才");

        String value = (String) session.getAttribute("name");
        if (value != null) {
            logger.info("shiro已经帮我们获取到了session回话对象当中指定的值：" + value);
        }

        if (currentUser.isAuthenticated() == false) {
            //UsernamePasswordToken
            UsernamePasswordToken token = new UsernamePasswordToken("root", "secret");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
                logger.info("用户名和密码正确，登陆成功");
            } catch (UnknownAccountException e) {
                logger.info("账户不存在。");
            } catch (IncorrectCredentialsException e) {
                logger.info("密码错误");
            } catch (LockedAccountException e) {
                logger.info("用户已锁死");
            } catch (AuthenticationException e) {
                logger.info("认证异常");
            }
        }

        if (currentUser.hasRole("goodguy")) {
            logger.info("拥有指定角色");
        } else {
            logger.info("未拥有指定角色");
        }

        //Subject:isPermitted(String);
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            logger.info("拥有指定权限");
        } else {
            logger.info("当前用户没有指定权限");
        }

        currentUser.logout();
        System.exit(0);
    }
}
